// 行号信息
import React from 'react';
import sha1 from 'sha1';
import { PopConfirm, Button, Balloon } from '@teamix/ui';
import './lineinfo.scss';
import intl from '../../../../../../../../../../../locale';

export default function LineInfo(props) {
  const { comment, maxWidth = '100px' } = props;
  if (!comment) {
    return null;
  }
  const { line, side, path, outdated } = comment;

  // outdated为true表示过期，跳转版本，定位行，需要传from_commit=？ &to_commit=
  let range_context = '';
  if (path && outdated && comment.range_context) {
    let [from_commit, to_commit] = comment.range_context.split(' ');
    if (from_commit && !to_commit) {
      to_commit = from_commit;
    }
    if (to_commit && !from_commit) {
      from_commit = to_commit;
    }
    range_context = `&from_commit=${from_commit}&to_commit=${to_commit}`;
  }
  /* path 不存在则没有为整体评论 */
  // 显示文件夹名称
  const curPathArr = comment.path ? comment.path.split('.') : [];
  if (!comment.path) {
    return null;
  }

  const outdatedTrigger = (
    <Button component="a" className="line-info-href" text type="primary">
      <Balloon.Tooltip
        trigger={
          <span
            className="one-line-ellipsis line-info-pathname"
            title={curPathArr[0]}
            style={{ maxWidth }}
          >
            {curPathArr[0]}
          </span>
        }
        align="b"
      >
        {curPathArr[0]}
      </Balloon.Tooltip>
      {!!curPathArr[1] && (
        <span style={{ display: 'inline-block', verticalAlign: 'middle' }}>.{curPathArr[1]}</span>
      )}
    </Button>
  );

  // 云豆过去不让跳转
  if (outdated && comment._comment_type === 'issue') {
    return outdatedTrigger;
  }
  return (
    <span>
      {!outdated ? (
        // 行数没有，则需要提示找不到，点击确认跳转到指定版本，查找指定行
        <Button
          component="a"
          type="primary"
          className="line-info-href"
          text
          onClick={(e) => {
            e.preventDefault();
            if (comment.is_draft) {
              props.closeDropdown && props.closeDropdown();
            } else {
              // 点击行号不收起
              // props.updateData && props.updateData({
              //   isShowComment: false,
              // });
            }
            // 如果hash不变，再次点击行号，直接滚动到指定位置
            const preHash = window.location.hash;
            const nextHash = `#file=${sha1(
              comment.path,
            )}&line=${line}&side=${side}${range_context}`;
            const lineAnchorDom = document.getElementById(
              `anchor_line_${sha1(comment.path)}_${side}_${line}`,
            );
            if (preHash === nextHash && lineAnchorDom) {
              const mrBody = document.querySelector('#mr-content-body');
              const parentOffsetHeight = lineAnchorDom.offsetParent
                ? lineAnchorDom.offsetParent.offsetTop
                : 0;
              mrBody.scrollTop = lineAnchorDom.offsetTop + parentOffsetHeight;
            } else {
              window.location.hash = nextHash;
            }
          }}
        >
          <Balloon.Tooltip
            trigger={
              <span
                className="one-line-ellipsis line-info-pathname"
                title={curPathArr[0]}
                style={{ maxWidth, display: 'inline-block' }}
              >
                {curPathArr[0]}
              </span>
            }
            align="b"
          >
            {curPathArr[0]}
          </Balloon.Tooltip>
          <span style={{ display: 'inline-block', verticalAlign: 'middle' }}>
            {!!curPathArr[1] && <span>.{curPathArr[1]}</span>}
            &nbsp; · &nbsp;
            <span>
              {intl.get(
                {
                  id: 'code-assets.components.commentMedia.lineInfo.LineLine',
                  defaultMessage: '第{line}行',
                },
                { line },
              )}
            </span>
          </span>
        </Button>
      ) : (
        <DeleteFileConfirm
          updateData={props.updateData}
          trigger={outdatedTrigger}
          hash={`#file=${sha1(comment.path)}${range_context}`}
        />
      )}
    </span>
  );
}

class DeleteFileConfirm extends React.Component {
  state = {
    visible: false,
  };

  onCancel = () => {
    this.setState({
      visible: false,
    });
  };

  onConfirm = () => {
    this.setState({
      visible: false,
    });

    this.props.updateData &&
      this.props.updateData({
        isShowComment: false,
      });

    window.location.hash = this.props.hash;
  };

  onVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  render() {
    const { visible } = this.state;
    return (
      <PopConfirm
        triggerType="click"
        align="b"
        title=""
        content={intl.get({
          id: 'code-assets.components.commentMedia.lineInfo.TheCommentHasExpiredDo',
          defaultMessage: '评论已过期，是否需要切换到发布该评论的提交版本？',
        })}
        onConfirm={this.onConfirm}
        onCancel={this.onCancel}
        visible={visible}
        offset={[37, 0]}
        onVisibleChange={this.onVisibleChange}
        trigger={this.props.trigger}
        followTrigger
        size="small"
      />
    );
  }
}
